'use strict';
var cmsDirectives = angular.module('cmsDirectives');

cmsDirectives.directive('templateSelection', ['$rootScope', 'Constant', 'SubscriptionOpt', 'cmsService', 'TemplateOpt',
    function ($rootScope, Constant, SubscriptionOpt, cmsService, TemplateOpt) {
        return {
            restrict: 'E',
            replace: true,
            //transclude: true,
            scope: {
                templateItems: '=ngModel'
            },
            link: function (scope, element, attrs) {
                scope.$watch('templateItems', function (newVal, oldVal) {
                    if (newVal) {
                        var items = newVal;
                        var ul = angular.element('<ul></ul>');
                        element.append(ul);
                        ul.jcarousel();

                        angular.forEach(items, function(item, i) {
                            var cls = item.code === $rootScope.CurrentSub.template ? 'active' : '';
                            var image = 'img/template/' + $rootScope.CurrentSub.code
                                + '/' + item.code + '.png';

                            ul.jcarousel('add', i + 1, [
                                '<li id="jcarousel-item--' + item.code + '--' + i + '" class="template-item ' + cls + '">',
                                '<div class="jcarousel-item-inner">',
                                '<div><img src="' + image + '" ></div>',
                                '<div class="text">' + item.name + '</div>',
                                '</div>',
                                '</li>'
                            ].join(''));
                        });
                        ul.jcarousel({
                            size: items.length,
                            scroll: 3,
                            visible: 3
                            //wrap: 'circular',
                            //itemFallbackDimension: 540
                        });

                        $(".jcarousel-container").delegate('li.template-item','click',function(e){
                                $('li.jcarousel-item').removeClass('active');
                                $(this).addClass('active');

                                var templateCode = $(this).attr('id').split('--')[1];
                                var json = SubscriptionOpt.opt({action: 'updateTemplate', subId: $rootScope.CurrentSub.id, template: templateCode},
                                    function() {
                                        $rootScope.CurrentSub.template = templateCode;
                                        $('li[id^="jcarousel-item--' + $rootScope.CurrentSub.id + '"').addClass('active');
                                });
                        });
                    }
                });
            }
        }
    }]);

